package com.example.xinai.Interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import com.example.xinai.Util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;


@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String secretKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");

        if (authorization == null || !authorization.startsWith("Bearer ")) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid token");
            return false;
        }

        String token = authorization.substring(7);
        JWT jwt = JWTUtil.parseToken(token);


       // 校验签名
        boolean verify = jwt.setKey(secretKey.getBytes(StandardCharsets.UTF_8)).verify();
        if (!verify) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            return false;
        }
        // 校验过期时间
        Object expObj = jwt.getPayload("exp");
        if (expObj != null) {
            long exp = Long.parseLong(expObj.toString());
            if (exp < System.currentTimeMillis()) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired");
                return false;
            }
        }

        Object usernameObj = jwt.getPayload("telephone");
        Object idObj = jwt.getPayload("userId");

        if (usernameObj == null || idObj == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token payload");
            return false;
        }

        String username = usernameObj.toString();
        int id = Integer.parseInt(idObj.toString());

        UserContext.setCurrentUser(username);
        UserContext.setCurrentId(id);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear(); // 清理 ThreadLocal
    }
}
